package devicedbgui;
import java.awt.BorderLayout;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.io.*;
import java.util.ArrayList;
import java.util.Properties;
import javax.swing.border.EmptyBorder;

/** Displays list of test cases available in selected exe file */
public class ListTC extends JDialog {
    /** Holds all class components */
    public JPanel p;
    /** Stores command to be sent as argument to exe file */
    public String[] command;
    /** Handles execution of exe file */
    public Process process;
    /** store exe command information */
    public ArrayList<String> ar; 
    public JCheckBox check;
    public boolean all=false;
      
    /** Constructor creates all components belonging to panel */
    public ListTC(JFrame parent,String exefile) {
        
    super(parent, "Test Cases", true);
    ar=new ArrayList<String>();
    ar.add(GUI.path);
    GridLayout layout = new GridLayout(0,1);
    JPanel pl=new JPanel();
    pl.add(new JLabel("Select the test cases you want to run:"));
 
    p=new JPanel();
    p.setLayout(layout);
    p.setBorder(new EmptyBorder(10,20,10,30));
    JScrollPane pne= new JScrollPane(p);
    layout.setVgap(7);
    GUI.testloaded=false;
     
    /* Reads available test cases from file */
    
    String fname=exefile;
    fname=fname.substring(0, fname.lastIndexOf('.'));
    try
   {   FileInputStream input;
       ar.add("test");
       Properties prop = new Properties(); 
       prop.load(input=new FileInputStream(fname+".ini"));
       int numb=Integer.parseInt(prop.getProperty("count"));
                            
       for (int i=1; i<numb+1; i++)
       {    String str=String.valueOf(prop.getProperty("Test"+i));
            JCheckBox cb = new JCheckBox(str);
            cb.setActionCommand(str);
            p.add(cb);
       }
           input.close();       
        } catch (FileNotFoundException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }         
      
      final JButton run= new JButton();
      run.setMnemonic(KeyEvent.VK_R);
      run.setText("Run");
      run.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent event) {
     getContentPane().setCursor(new Cursor(Cursor.WAIT_CURSOR)); 
          TestCasesActionPerformed(event);
      GUI.testloaded=true;
     
      // launch EXE and grab stdin/stdout and stderr
      Process theProcess = null;
      BufferedReader inStream = null;
 
      String[] stringArray = (String[])ar.toArray(new String[ar.size()]);
     
      try
      { System.out.print(ar+"----------");
          theProcess = Runtime.getRuntime().exec(stringArray);
           theProcess.waitFor();
           
      }
                catch (InterruptedException ex) {
                    Logger.getLogger(ListTC.class.getName()).log(Level.SEVERE, null, ex);
                }      catch(IOException e)
      {
         System.err.println("Error on exec() method");
         e.printStackTrace();  
      }
        
      // read from the called program's standard output stream
      try
      {
         inStream = new BufferedReader(
         new InputStreamReader( theProcess.getInputStream() ));  
         System.out.println(inStream.readLine());
         inStream.close();
      }
      catch(IOException e)
      {
         System.err.println("Error on inStream.readLine()");
         e.printStackTrace();  
      }

      setVisible(false);
                
  
         }});
         
          JButton cancel=new JButton("Cancel");
          cancel.setMnemonic(KeyEvent.VK_ESCAPE);
          cancel.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
                     GUI.testloaded=false;
                     dispose();
             }});
             
             
        JPanel buttonPane= new JPanel();
        check=new JCheckBox("Select All");
        check.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllActionPerformed(evt);
            }
        });
        
        buttonPane.add(check);
        buttonPane.add(run);  
        buttonPane.add(cancel);
        
        getContentPane().add(pl, BorderLayout.NORTH);
        getContentPane().add(pne, BorderLayout.CENTER);
        getContentPane().add(buttonPane, BorderLayout.SOUTH);
 
    pack();
    setLocationRelativeTo(null);
    setSize(400,300);
   
      }
    
    private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (check.isSelected()){ all=true;}
    else {all=false;}
    Component[] comps = p.getComponents();
  
    // for each JCheckBox component...
    for( Component component : comps )
    {
        JCheckBox checkBox = (JCheckBox)component;
       checkBox.setSelected(all);                         
    } // end of for loop

                              
}
/** Reads which test cases to run based on check boxes */
private void TestCasesActionPerformed(java.awt.event.ActionEvent evt) {                                                    
    
    // get all the JCheckBox components
    Component[] comps = p.getComponents();
  
    // for each JCheckBox component...
    for( Component component : comps )
    {
        JCheckBox checkBox = (JCheckBox)component;
        
        // if the checkbox is not selected then continue the loop
        if ( !checkBox.isSelected() )
        {    
        continue;}
        
        // the checkbox is selected
       // get the actionCommand of the checkbox
        // the actionCommand is the test case number
        ar.add(checkBox.getActionCommand());
                    
    } // end of for loop
 }                                      
}